<!--
 * @Descripttion: 
 * @Author: jhw
 * @Date: 2023-05-15 22:19:56
 * @LastEditors: jhw
 * @LastEditTime: 2023-05-17 20:57:14
-->
<template>
  <div ref="parentRef" class="watermark-container">
    <slot> </slot>
    <!-- 添加一个div，填充整个区域，设置水印，重复 -->
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, watchEffect } from 'vue';
import useWatermarkBg from './useWatermarkBg';

const props = defineProps({
  text: {
    type: String,
    required: true,
    default: 'watermark',
  },
  fontSize: {
    type: Number,
    default: 40,
  },
  // 间隙
  gap: {
    type: Number,
    default: 20,
  },
});

const parentRef = ref();
const bg = useWatermarkBg(props);
let ob: any;
let div: any;
const flag = ref(0);

watchEffect(() => {
  flag.value;
  if (!parentRef.value) {
    return;
  }
  if (div) {
    div.remove();
  }
  const { base64, styleSize } = bg.value;
  div = document.createElement('div');
  div.style.backgroundImage = `url(${base64})`;
  div.style.backgroundSize = `${styleSize}px ${styleSize}px`;
  div.style.backgroundRepeat = 'repeat';
  div.style.width = '100%';
  div.style.height = '100%';
  div.style.zIndex = '9999';
  div.style.pointerEvents = 'none'; // 防止水印遮挡底部点击事件
  div.style.position = 'absolute';
  div.style.inset = '0';
  parentRef.value.appendChild(div);
});

onMounted(() => {
  // document.onselectstart = () => false; // 禁止选中
  ob = new MutationObserver((records) => {
    console.log(records);
    for (const record of records) {
      // 删除水印
      for (const dom of record.removedNodes) {
        if (dom === div) {
          flag.value++;
          return;
        }
      }
      // 修改水印
      if (record.target === div) {
        flag.value++;
        return;
      }
    }
  });
  ob.observe(parentRef.value, {
    childList: true,
    attributes: true,
    subtree: true,
  });
});

onUnmounted(() => {
  ob && ob.disconnect(); // 取消监听
});
</script>

<style scoped>
.watermark-container {
  position: relative;
}
</style>
